﻿using WebApplication1.Core.DataTransferObject;
using WebApplication1.Core.Domain.Entities;
using WebApplication1.Core.Domain.RepositoryContracts;
using WebApplication1.Core.ServiceContracts;

namespace WebApplication1.Core.Services {
    public class LouYuanService : ILouYuanService {

        private readonly ILouYuanRepository _LouYuanRepository;

        public LouYuanService(ILouYuanRepository LouYuanRepository) {
            _LouYuanRepository = LouYuanRepository;
        }

        public async Task<LouYuanResponse> AddLouYuan(LouYuanRequest? LouYuanAddRequest) {
            if(LouYuanAddRequest == null) {
                throw new ArgumentNullException(nameof(LouYuanAddRequest));
            }
            LouYuan temp = LouYuanAddRequest.ToLouYuan();
            //temp.LouYuanID = Guid.NewGuid();
            LouYuan addedLouYuan = await _LouYuanRepository.AddLouYuan(temp);
            return addedLouYuan.ToLouYuanResponse();
        }

        public async Task<bool> DeleteLouYuan(ushort? LouYuanID) {
            if(LouYuanID == null) { throw new ArgumentNullException(nameof(LouYuanID)); }
            bool result = await _LouYuanRepository.DeleteLouYuan(LouYuanID.Value);
            return result;
        }

        public async Task<IEnumerable<LouYuanResponse>> GetAllLouYuan() {
            IEnumerable<LouYuan> allLouYuan = await _LouYuanRepository.GetAllLouYuan();
            return allLouYuan.Select(LouYuan => LouYuan.ToLouYuanResponse());
        }

        public async Task<IEnumerable<LouYuanResponse>?> GetLouYuanByMingCheng(string? mingCheng) {
            if(mingCheng == null) { throw new ArgumentNullException(nameof(mingCheng)); }
            IEnumerable<LouYuan> filterResult = await _LouYuanRepository.GetFilteredLouYuan(LouYuan => LouYuan.MingCheng.Contains(mingCheng));
            return filterResult.Select(temp => temp.ToLouYuanResponse());
        }

        public async Task<LouYuanResponse?> GetLouYuanByLouYuanID(ushort? LouYuanID) {
            if(LouYuanID == null) { throw new ArgumentNullException(nameof(LouYuanID)); }
            LouYuan? result = await _LouYuanRepository.GetLouYuanByLouYuanID(LouYuanID.Value);
            return result?.ToLouYuanResponse();
        }

        public async Task<LouYuanResponse?> UpdateLouYuan(LouYuanRequest? LouYuanUpdateRequest) {
            if(LouYuanUpdateRequest == null) { throw new ArgumentNullException(nameof(LouYuanUpdateRequest)); }
            bool isSuccess = await _LouYuanRepository.UpdateLouYuan(LouYuanUpdateRequest.ToLouYuan());
            if(isSuccess) {
                return LouYuanUpdateRequest.toLouYuanResponse();
            } else {
                return null;
            }
        }
    }
}
